package edu.polsl.bio.str.manager.error;

import edu.polsl.bio.str.common.constant.NodeState;
import edu.polsl.bio.str.common.entity.Node;
import edu.polsl.bio.str.common.messaging.StrJobPayload;
import edu.polsl.bio.str.manager.dao.JobDao;
import edu.polsl.bio.str.manager.dao.NodeDao;
import edu.polsl.bio.str.manager.messaging.QueueLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * //todo class description
 * <p/>
 * Created on: Jul 15, 2011 2:05:42 PM <br/>
 * <a href="http://www.polsl.pl">www.polsl.pl</a>
 *
 * @author lukasz.olczak@polsl.pl
 */
public class NodeCommunicationErrorHandlerImpl implements NodeCommunicationErrorHandler {
  /**
   * slf4j Logger.
   */
  private static final Logger log = LoggerFactory.getLogger(NodeCommunicationErrorHandlerImpl.class.getName());

  private NodeDao nodeDao;

  private JobDao jobDao;

  private QueueLocator queueLocator;

  @Override
  @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
  public void handleError(String nodeIp, StrJobPayload payload, Exception ex) {
    log.debug("Handling communication error for node {}", nodeIp);
    Node node = nodeDao.findByIp(nodeIp);
    node.setNodeState(NodeState.DETACHED);
    nodeDao.update(node);
    queueLocator.flushProxy(node.getNodeIp());
    int count = jobDao.invalidateJobs(node.getId());
    log.debug("{} jobs will be rescheduled", count);
  }

  public void setJobDao(JobDao jobDao) {
    this.jobDao = jobDao;
  }

  public void setNodeDao(NodeDao nodeDao) {
    this.nodeDao = nodeDao;
  }

  public void setQueueLocator(QueueLocator queueLocator) {
    this.queueLocator = queueLocator;
  }
}
